package com.skywolf.chem.customer.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.skywolf.chem.common.enums.ResponseCodeEnum;
import com.skywolf.chem.common.sysconfig.response.RespData;
import com.skywolf.chem.customer.entity.Customer;
import com.skywolf.chem.customer.param.CustomerParam;
import com.skywolf.chem.customer.param.LoginDto;
import com.skywolf.chem.customer.service.ICustomerService;
import com.skywolf.chem.tencent.service.ImService;
import com.skywolf.chem.utils.CryptUtil;
import com.skywolf.chem.utils.IDCardUtil;
import com.skywolf.chem.utils.PhoneUtils;
import com.skywolf.chem.utils.RequestConstans;
import com.skywolf.chem.utils.sms.TXSendMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author 
 * @since 2020-11-29
 */
@RestController
@RequestMapping("/edu/customer/login")
@Api(value = "API登录注册相关接口", description = "API登录注册相关接口")
public class LoginController {

    @Autowired
    ICustomerService customerService;

    @Autowired
    ImService imService;

    @ApiOperation(value = "注册短信",notes = "注册短信")
    @RequestMapping(value = "/registerMsg",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> registerMsg(HttpServletRequest request, @RequestBody CustomerParam param) {
        if(param==null || !PhoneUtils.phoneCheck(param.getPhone())){
            return RespData.failure(ResponseCodeEnum.PHONE_ERROR);
        }
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", param.getPhone());
        Customer user = customerService.getOne(queryWrapper);
        if(user != null && StringUtils.isNotBlank(user.getPassword())){
            return RespData.failure(ResponseCodeEnum.PHONE_DUPLICATE);
        }
        String code = PhoneUtils.getCode();
        Boolean bl = TXSendMsg.sendMsg(param.getPhone(), code,"registerMsg");
        if(!bl){
            return RespData.failResult("短信发送失败");
        }
        if(user==null){
            user = new Customer();
            String userName = IDCardUtil.getStringRandom(8);
            if(StringUtils.isNotBlank(param.getUserName())){
                userName = param.getUserName();
            }
            user.setUserName(userName);
            user.setCode(code);
            user.setPhone(param.getPhone());
            user.setCodeTime(LocalDateTime.now());
            customerService.save(user);
        }else{
            String userName = IDCardUtil.getStringRandom(8);
            if(StringUtils.isNotBlank(param.getUserName())){
                userName = param.getUserName();
            }
            user.setUserName(userName);
            user.setPhone(param.getPhone());
            user.setCode(code);
            user.setCodeTime(LocalDateTime.now());
            customerService.updateById(user);
        }
        return RespData.success("success");
    }

    @ApiOperation(value = "注册",notes = "注册")
    @RequestMapping(value = "/register",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> register(HttpServletRequest request, @RequestBody CustomerParam param) {
        if(param==null || !PhoneUtils.phoneCheck(param.getPhone())){
            return RespData.failure(ResponseCodeEnum.PHONE_ERROR);
        }
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", param.getPhone());
        Customer user = customerService.getOne(queryWrapper);
        if(user == null){
            return RespData.failure(ResponseCodeEnum.ACCOUNT_ERROR);
        }
        if(StringUtils.isNotBlank(param.getUserName())){
            user.setUserName(param.getUserName());
        }
        Long nowTime = System.currentTimeMillis()/1000;
        Long codeTime = user.getCodeTime().toEpochSecond(ZoneOffset.of("+8"));
        if(nowTime-codeTime>300){
            return RespData.failure(ResponseCodeEnum.CODE_EXPIRE);
        }
        if(!user.getCode().equals(param.getMsgCode())){
            return RespData.failure(ResponseCodeEnum.CODE_ERROR);
        }
        user.setPassword(CryptUtil.encryptAES128(param.getPassword(), RequestConstans.decode_pwd));
        customerService.updateById(user);
        return RespData.success("success");
    }

    @ApiOperation(value = "登录",notes = "登录")
    @RequestMapping(value = "/loginUser",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<LoginDto> loginUser(HttpServletRequest request, @RequestBody CustomerParam param) {
        if(param==null || !PhoneUtils.phoneCheck(param.getPhone())){
            return RespData.failure(ResponseCodeEnum.PHONE_ERROR);
        }
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", param.getPhone());
        Customer user = customerService.getOne(queryWrapper);
        user.setLoginTime(LocalDateTime.now());
        if(user == null){
            return RespData.failure(ResponseCodeEnum.ACCOUNT_ERROR);
        }
        String password = CryptUtil.encryptAES128(param.getPassword(), RequestConstans.decode_pwd);
        if(password.equals(user.getPassword())){
            String token = user.getId()+"|"+user.getPhone()+"|"+user.getPassword()+"|"+System.currentTimeMillis()/1000;
            String userToken = CryptUtil.IMDes3Encode(token, RequestConstans.decode_pwd);
            LoginDto loginParam = new LoginDto();
            loginParam.setToken(userToken);
            loginParam.setUid(user.getId());
            String imSig = imService.getUseSig(user.getId()+"",null);
            loginParam.setImUserSig(imSig);
            loginParam.setUserName(user.getUserName());
            loginParam.setHeadImg(user.getHeadImg());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            String formattedDateTime = user.getLoginTime().format(formatter); // "1986-04-08 12:30"
            loginParam.setLoginTime(formattedDateTime);
            return RespData.success(loginParam);
        }else{
            return RespData.failure(ResponseCodeEnum.PWD_ERROR);
        }
    }

}
